import { defineComponent, createVNode, render, reactive } from "vue";
import { ElButton, ElDialog, ElInput } from "element-plus";
const dialogComponent = defineComponent({
  props: {
    option: { type: Object },
  },
  setup(props, ctx) {
    const state = reactive({ option: props.option, isShow: false });
    ctx.expose({
      // 让外部可以调用
      showDialog(option) {
        state.option = option;
        state.isShow = true;
      },
    });
    const onCancel = () => {
      state.isShow = false;
    };
    const onConfirm = () => {
      state.isShow = false;
      state.option.onConfirm && state.option.onConfirm(state.option.content);
    };
    return () => {
      return (
        <ElDialog v-model={state.isShow} title={state.option.title}>
          {{
            default: () => {
              return (
                <ElInput
                  type="textarea"
                  rows="10"
                  v-model={state.option.content}
                ></ElInput>
              );
            },
            footer: () =>
              state.option.footer && (
                <div>
                  <ElButton onClick={onCancel}>取消</ElButton>
                  <ElButton onClick={onConfirm} type="primary">
                    确定
                  </ElButton>
                </div>
              ),
          }}
        </ElDialog>
      );
    };
  },
});
let vNode;
export function $dialog(option) {
  // element-plus vs一直 el-dialog 组件
  // 手动挂在组件 new Subcomponent.$mount()
  if (!vNode) {
    const el = document.createElement("div");
    // 将组件渲染成虚拟节点
    vNode = createVNode(dialogComponent, { option });
    // 渲染成真实节点挂载到页面中
    document.body.append((render(vNode, el), el));
  }
  // 手动挂在组件
  let { showDialog } = vNode.component.exposed;
  showDialog(option);
}
